package cn.wenhe9.hefengweather.ui.weather

import android.content.Context
import android.graphics.Color
import android.media.Image
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowInsetsController
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.GravityCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import cn.wenhe9.hefengweather.R
import cn.wenhe9.hefengweather.databinding.ActivityWeatherBinding
import cn.wenhe9.hefengweather.logic.model.Weather
import cn.wenhe9.hefengweather.logic.model.getSky
import org.w3c.dom.Text

class WeatherActivity : AppCompatActivity() {

    private lateinit var binding : ActivityWeatherBinding

    val viewModel by lazy {
        ViewModelProvider(this).get(WeatherViewModel::class.java)
    }

    val swiperRefresh by lazy {
        binding.swiperRefresh
    }

    val drawerLayout by lazy {
        binding.drawerLayout
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWeatherBinding.inflate(layoutInflater)
        setContentView(binding.root)

        WindowCompat.setDecorFitsSystemWindows(window, false)
        WindowInsetsControllerCompat(window, binding.root).let { controller ->
            controller.hide(WindowInsetsCompat.Type.systemBars())
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                controller.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            }
        }

        if(viewModel.locationId.isEmpty()){
            viewModel.locationId = intent.getStringExtra("locationId") ?: ""
        }
        if (viewModel.placeName.isEmpty()){
            viewModel.placeName = intent.getStringExtra("placeName") ?: ""
        }

        viewModel.weatherLiveData.observe(this, Observer { result ->
            val weather = result.getOrNull()

            if (weather != null){
                showWeather(weather)
            }else{
                Toast.makeText(this, "无法成功获取天气信息", Toast.LENGTH_SHORT).show()
                result.exceptionOrNull()?.printStackTrace()
            }

            swiperRefresh.isRefreshing = false
        })

        swiperRefresh.setColorSchemeResources(R.color.design_default_color_primary)
        refreshWeather()
        swiperRefresh.setOnRefreshListener {
            refreshWeather()
        }


        binding.nowLayout.navBtn.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.START)
        }

        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener{
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {

            }

            override fun onDrawerOpened(drawerView: View) {

            }

            override fun onDrawerClosed(drawerView: View) {
                val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

                manager.hideSoftInputFromWindow(drawerView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }

            override fun onDrawerStateChanged(newState: Int) {

            }

        })

    }

    private fun showWeather(weather : Weather){
        binding.nowLayout.placeName.text = viewModel.placeName

        val realtime = weather.realTime
        val daily = weather.daily
        val lifeIndex = weather.lifeIndex

        //填充now.xml布局中的数据
        val nowLayout = binding.nowLayout
        val currentTempText = "${realtime.temp.toInt()} ℃"
        val currentWindText ="${realtime.windDir} ${realtime.windScale}级"
        nowLayout.currentTemp.text = currentTempText
        nowLayout.currentSky.text = getSky(realtime.icon).info
        nowLayout.currentWind.text = currentWindText

        nowLayout.nowLayout.setBackgroundResource(getSky(realtime.icon).bg)

        //填充forecast.xml布局中的数据
        val forecastLayout = binding.forecast
        forecastLayout.forecastLayout.removeAllViews()

        val days = daily.size

        for( i in 0 until days){
            val skycon = daily[i]

            val tempMax = skycon.tempMax
            val tempMin = skycon.tempMin

            val view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout.forecastLayout, false)

            val dateInfo = view.findViewById<TextView>(R.id.dateInfo)
            val skyIcon = view.findViewById<ImageView>(R.id.skyIcon)
            val skyInfo = view.findViewById<TextView>(R.id.skyInfo)
            val temperatureInfo = view.findViewById<TextView>(R.id.temperatureInfo)

            dateInfo.text = skycon.fxDate
            val sky = getSky(skycon.iconDay)
            skyInfo.text = sky.info
            skyIcon.setImageResource(sky.icon)
            val tempText = "${tempMin.toInt()} ~ ${tempMax.toInt()} ℃"
            temperatureInfo.text = tempText

            forecastLayout.forecastLayout.addView(view)
        }


        //填充life_index.xml布局中的数据
        val lifeIndexLayout = binding.lifeIndexLayout

        lifeIndexLayout.coldRiskText.text = lifeIndex[3].category
        lifeIndexLayout.dressingText.text = lifeIndex[2].category
        lifeIndexLayout.cardWashingText.text = lifeIndex[1].category
        lifeIndexLayout.ultrravioletText.text = lifeIndex[0].category

        binding.weatherLayout.visibility = View.VISIBLE
    }

    fun refreshWeather(){
        viewModel.refreshWeather(viewModel.locationId)
        swiperRefresh.isRefreshing = true
    }
}